import Phaser from 'phaser';
import Bullet from '../sprite/bullet.js';

export default class PlayGame extends Phaser.Scene{

    constructor(){
        super('playGame');
        this.shipSpeed=1000;
    }

    create(){
        const {width, height} = this.scale;

        // bg
        let spaceBg = this.add.tileSprite(0, 0, width, height, 'space_bg');
        spaceBg.setOrigin(0, 0);
        spaceBg.setScrollFactor(0);
        this.spaceBg=spaceBg;

        // ship
        this.ship = this.physics.add.sprite(width/2, height/2, 'ship');
        this.ship.setInteractive();
        this.ship.setCollideWorldBounds(true);

        // camera
        // this.myCam = this.cameras.main.startFollow(this.ship);

        // this.add.text(20, 20, '开始游戏', {color:'#333'});
        this.input.on('gameobjectdown', this.destroyShip, this);

        // bullets
        this.bullets = this.add.group();

        // input
        this.cursorKeys = this.input.keyboard.createCursorKeys();
        // space Key
        this.spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

    }

    update() {
        this.moveShip();
        // this.spaceBg.tilePositionY = this.myCam.scrollY*.3;
        // this.spaceBg.tilePositionX = this.myCam.scrollX*.3;
        const bullets = this.bullets;
        for(let i = 0, len =bullets.getChildren().length;i<len;i++){
            const bullet= bullets.getChildren()[i];
            bullet&&bullet.update();
        }

        if(Phaser.Input.Keyboard.JustDown(this.spaceBar)){
            if(!this.ship.visible) return;
            this.shoot()
        }

    }

    moveShip() {

        if(this.cursorKeys.left.isDown){
            this.ship.setVelocityX(-this.shipSpeed);
        }else if(this.cursorKeys.right.isDown){
            this.ship.setVelocityX(this.shipSpeed);
        }

        if(this.cursorKeys.up.isDown){
            this.ship.setVelocityY(-this.shipSpeed);
        }else if(this.cursorKeys.down.isDown){
            this.ship.setVelocityY(this.shipSpeed);
        }
    }

    shoot(){
        new Bullet(this);
    }

    destroyShip(pointer, gameObj){
        gameObj.setTexture('boom');
        gameObj.play('boom');
    }

}